import {Layout, Menu, Icon, Row, Col, Modal} from 'antd';
import React, {Component} from 'react';
import logo from '../image/logo.jpg';
import {Link, Route, Switch} from 'react-router-dom';
import '../css/login.css';
import {config} from '../config';
import app from '../app';
import Admin from './Admin';//管理员账号管理
import MenuList from './MenuList';//菜单管理
import PositionManage from './PositionManage';//职位管理
import CarouselList from './CarouselList';//首页轮播图广告
import ActivityList from './ActivityList';//满减活动列表
import ActivityAdd from './ActivityAdd';//新增满减活动
import Invitation from './Invitation';//邀请奖励
import TeamBuying from './TeamBuying';//团购活动
import RedPacket from './RedPacket';//红包
import StoreSetup from './StoreSetup';//店铺设置
import OperationalSetup from './OperationalSetup';//运营设置
import TransportTemplate from './PostTemplate/TransportTemplate';//运费模板
import AddTransport from './PostTemplate/AddTransport';//添加运费模板
import EditTransport from './PostTemplate/EditTransport';//修改运费模板
import UserManage from './UserManage';//用户管理
import OrderList from './OrderList';//订单管理
import OrderDetail from './OrderDetail';//订单详情
import SupplierManage from './SupplierManage';//供应商管理
import TypeManage from './TypeManage';//商品分类
import SkuManage from './SkuManage';//属性管理
import GoodsManage from './GoodsManage';//商品管理
import GoodsAdd from './GoodsAdd';//添加商品
import GoodsEdit from './GoodsEdit';//修改商品
import RechargeSetting from './RechargeSetting';//充值设置
import RechargeRecord from './RechargeRecord';//充值记录
import TeamBuyingList from './TeamBuyingList';//团购活动列表
import TeamBuyingEdit from './TeamBuyingEdit';//编辑团购活动

import exit from '../image/exit.png';
import admin from '../image/admin.png';

const path = config.path;
const {SubMenu} = Menu;
const confirm = Modal.confirm;
const {Header, Content, Sider} = Layout;

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false,
            key: '0',
            username: '',
            menuList: [
                {component: Admin, menu_path: '/home/admin', menu_icon: 'smile', menu_name: '管理员账号管理'},
                {component: MenuList, menu_path: '/home/menuList', menu_icon: 'smile', menu_name: '菜单管理'},
                {component: PositionManage, menu_path: '/home/positionManage', menu_icon: 'smile', menu_name: '职位管理'},
                {component: CarouselList, menu_path: '/home/carouselList', menu_icon: 'smile', menu_name: '首页轮播图广告'},
                {
                    menu_icon: 'smile',
                    menu_name: '营销活动',
                    subList: [
                        {component: ActivityList, menu_path: '/home/activityList', menu_icon: 'smile', menu_name: '满减活动列表'},
                        {component: Invitation, menu_path: '/home/invitation', menu_icon: 'smile', menu_name: '邀请奖励'},
                        {component: TeamBuyingList, menu_path: '/home/teamBuyingList', menu_icon: 'smile', menu_name: '团购活动列表'},
                        {component: RedPacket, menu_path: '/home/redPacket', menu_icon: 'smile', menu_name: '红包'},
                    ]
                },
                {
                    menu_icon: 'smile',
                    menu_name: '店铺设置',
                    subList: [
                        {component: StoreSetup, menu_path: '/home/storeSetup', menu_icon: 'smile', menu_name: '店铺设置'},
                        {component: OperationalSetup, menu_path: '/home/operationalSetup', menu_icon: 'smile', menu_name: '运营设置'},
                        {component: TransportTemplate, menu_path: '/home/transportTemplate', menu_icon: 'smile', menu_name: '运费模板设置'},
                        {component: RechargeSetting, menu_path: '/home/rechargeSetting', menu_icon: 'smile', menu_name: '充值设置'},
                        {component: RechargeRecord, menu_path: '/home/rechargeRecord', menu_icon: 'smile', menu_name: '充值记录'},
                    ]
                },
                {component: UserManage, menu_path: '/home/userManage', menu_icon: 'smile', menu_name: '用户管理'},
                {component: OrderList, menu_path: '/home/orderList', menu_icon: 'smile', menu_name: '订单管理'},
                {
                    menu_icon: 'smile',
                    menu_name: '商品管理',
                    subList: [
                        {component: SupplierManage, menu_path: '/home/supplierManage', menu_icon: 'smile', menu_name: '供应商管理'},
                        {component: TypeManage, menu_path: '/home/typeManage', menu_icon: 'smile', menu_name: '商品分类'},
                        {component: SkuManage, menu_path: '/home/skuManage', menu_icon: 'smile', menu_name: '属性管理'},
                        {component: GoodsManage, menu_path: '/home/goodsManage', menu_icon: 'smile', menu_name: '商品管理'},
                    ]
                },
            ],
            openSubMenuKey: '',
            currentKey: path + '/home/successfulCases', //选中的菜单
        };
    }

    routeList = [
        {component: Admin, menu_path: '/home/admin', menu_icon: 'smile', menu_name: '管理员账号管理'},
        {component: MenuList, menu_path: '/home/menuList', menu_icon: 'smile', menu_name: '菜单管理'},
        {component: PositionManage, menu_path: '/home/positionManage', menu_icon: 'smile', menu_name: '职位管理'},
        {component: CarouselList, menu_path: '/home/carouselList', menu_icon: 'smile', menu_name: '首页轮播图广告'},
        {component: ActivityList, menu_path: '/home/activityList', menu_icon: 'smile', menu_name: '满减活动列表'},
        {component: ActivityAdd, menu_path: '/home/activityAdd/:id', menu_icon: 'smile', menu_name: '新增满减活动'},
        {component: Invitation, menu_path: '/home/invitation', menu_icon: 'smile', menu_name: '邀请奖励'},
        {component: TeamBuyingList, menu_path: '/home/teamBuyingList', menu_icon: 'smile', menu_name: '团购活动列表'},
        {component: TeamBuying, menu_path: '/home/teamBuying', menu_icon: 'smile', menu_name: '团购活动'},
        {component: TeamBuyingEdit, menu_path: '/home/teamBuyingEdit/:id', menu_icon: 'smile', menu_name: '编辑团购活动'},
        {component: RedPacket, menu_path: '/home/redPacket', menu_icon: 'smile', menu_name: '红包'},
        {component: StoreSetup, menu_path: '/home/storeSetup', menu_icon: 'smile', menu_name: '店铺设置'},
        {component: OperationalSetup, menu_path: '/home/operationalSetup', menu_icon: 'smile', menu_name: '运营设置'},
        {component: TransportTemplate, menu_path: '/home/transportTemplate', menu_icon: 'smile', menu_name: '运费模板设置'},
        {component: AddTransport, menu_path: '/home/addTransport', menu_icon: 'smile', menu_name: '添加运费模板'},
        {component: EditTransport, menu_path: '/home/editTransport', menu_icon: 'smile', menu_name: '修改运费模板'},
        {component: UserManage, menu_path: '/home/userManage', menu_icon: 'smile', menu_name: '用户管理'},
        {component: OrderList, menu_path: '/home/orderList', menu_icon: 'smile', menu_name: '订单管理'},
        {component: OrderDetail, menu_path: '/home/orderDetail/:id', menu_icon: 'smile', menu_name: '订单详情'},
        {component: SupplierManage, menu_path: '/home/supplierManage', menu_icon: 'smile', menu_name: '供应商管理'},
        {component: TypeManage, menu_path: '/home/typeManage', menu_icon: 'smile', menu_name: '商品分类'},
        {component: SkuManage, menu_path: '/home/skuManage', menu_icon: 'smile', menu_name: '属性管理'},
        {component: GoodsManage, menu_path: '/home/goodsManage', menu_icon: 'smile', menu_name: '商品管理'},
        {component: GoodsAdd, menu_path: '/home/goodsAdd', menu_icon: 'smile', menu_name: '添加商品'},
        {component: GoodsEdit, menu_path: '/home/goodsEdit/:id', menu_icon: 'smile', menu_name: '修改商品'},
        {component: RechargeSetting, menu_path: '/home/rechargeSetting', menu_icon: 'smile', menu_name: '充值设置'},
        {component: RechargeRecord, menu_path: '/home/rechargeRecord', menu_icon: 'smile', menu_name: '充值记录'},
    ];

    render() {
        return (
            <span style={{height: '100%'}}>
                <Layout style={{height: '100%'}}>
                    <Sider width={200} style={{overflowY: 'auto', overflowX: 'hidden',}} className="hiddenScroll">
                             <span style={{
                                 display: 'inline-block',
                                 width: '200px',
                                 height: '110px',
                                 backgroundColor: 'white'
                             }}>
                                 <img width={'200px'} height={'110px'}
                                      style={{position: 'relative'}} src={logo} alt=""/>
                             </span>
                        <Menu mode="inline"
                              theme="dark"
                              selectedKeys={[this.state.currentKey]}
                              openKeys={[this.state.openSubMenuKey+'']}
                              onClick={(item) => this.handleMenuClick(item)}>
                            {
                                this.state.menuList.map((item, index) => {
                                    if (item.subList) {
                                        return (
                                            <SubMenu onTitleClick={(value) => {
                                                this.handleClickSubMenu(value, index)
                                            }} key={index}
                                                     title={<span><Icon type={item.menu_icon}/>{item.menu_name}</span>}>
                                                {
                                                    item.subList.map((subItem, subIndex) => {
                                                        return (
                                                            <Menu.Item key={path + subItem.menu_path}
                                                                       rowKey={index + "" + subIndex}>
                                                        <span>
                                                            {/*<Icon type={subItem.menu_icon}/>*/}
                                                            <Icon type='plus-square-o'/>
                                                            <span>{subItem.menu_name}</span>
                                                        </span>
                                                            </Menu.Item>
                                                        )
                                                    })
                                                }
                                            </SubMenu>)
                                    } else {
                                        return (
                                            <Menu.Item key={path + item.menu_path} rowKey={index}>
                                            <span>
                                                {/*<Icon type={item.menu_icon}/>*/}
                                                <Icon type='plus-square-o'/>
                                                <span>{item.menu_name}</span>
                                            </span>
                                            </Menu.Item>
                                        )
                                    }
                                })
                            }
                        </Menu>
                    </Sider>
                    <Layout>
                        <Header
                            style={{color: 'white', backgroundColor: '#404040', height: '110px', lineHeight: '110px'}}>
                            <Row>
                                <Col span={24}
                                     style={{
                                         display: 'flex',
                                         fontSize: '25px',
                                         justifyContent: 'center'
                                     }}>社区电商后台管理系统</Col>
                                <div style={{position: 'absolute', right: '0px', fontSize: '17px', display: 'flex'}}>
                                    <span style={{marginRight: '5px', marginTop: 4}}><img src={admin} style={{
                                        width: 24,
                                        height: 24
                                    }}/>
                                    </span>
                                    <span style={{color: 'red', marginRight: '20px'}}>{this.state.username}</span>
                                    <span className="exit" style={{marginRight: '10px'}} onClick={() => {
                                        this.handleExit()
                                    }}>退出</span>
                                    <span className="exit" style={{marginRight: '10px', marginTop: 4}} onClick={() => {
                                        this.handleExit()
                                    }} title="退出"><img src={exit} style={{width: 20, height: 20}}/></span>
                                </div>
                            </Row>
                        </Header>
                        <Content style={{
                            background: '#fff',
                            padding: '10px 24px 24px 24px',
                            margin: 24,
                            position: 'relative'
                        }}>
                            <Switch>
                                {
                                    this.routeList.map((item, index) => {
                                        return <Route key={index} path={path + item.menu_path}
                                                      component={item.component}/>
                                    })
                                }
                            </Switch>
                            <div className="footer">
                                技术支持：佛山市领蓝信息科技有限公司
                            </div>
                        </Content>
                    </Layout>
                </Layout>
            </span>
        )
    }

    // 跳转页面菜单的显示控制
    componentWillReceiveProps(props) {
        let tempPath = props.location.pathname;
    }

    componentDidMount() {
        window._this = this;
        let username = app.getData('username');
        this.setState({username});
        // 判断是否登录
        if (!app.getToken()) {
            app.alert('请重新登录', 'error', 3);
            this.props.history.push(path + '/login');
        } else {
            const key = app.getData('pathPlatform');  //保存之前点过的菜单
            if (key) {
                //this.handleMenuClick({key});
                this.setState({
                    currentKey: key
                });
            }
        }
        app.scrollTop();
        // 获得权限
        if ('Notification' in window) {  //判断当前浏览器是否支持通知的功能
            Notification.requestPermission(); //作用就是让浏览器出现是否允许通知的提示
        }
        else {
            app.alert('当前浏览器不支持通知的功能', 'info', 3)
        }
        window._this = this;
        this.removePageStatus();   // 点击菜单时，清空跳转页面所保存的状态
        let selectMenu = app.getData('pathPlatform');
        let subMenuKey = app.getData('subMenuKeyPlatform');
        let token = app.getToken();
        let currentKey;
        let openSubMenuKey;
        if (!token) {
            this.handleConsoleToken();
        }
        else {
            let firstMenu = [];
            if (selectMenu) {
                currentKey = selectMenu
            }
            if (!selectMenu) {
                currentKey = path + firstMenu[0].menu_path
            }

            if (subMenuKey) {
                openSubMenuKey = subMenuKey
            }
            if (!subMenuKey) {
                openSubMenuKey = ''
            }

            this.setState({
                currentKey: currentKey,
                openSubMenuKey: openSubMenuKey,
            })
        }
    }

    // handleMenuClick({key}) {
    //     app.scrollTop();
    //     window._this = this;
    //
    //     let token = app.getToken();
    //     if (!token) {
    //
    //     } else {
    //         this.setState({
    //             currentKey: key
    //         });
    //         app.setData('currentKey', key);
    //         this.props.history.push(key);
    //     }
    // }

    //点击有下级菜单的菜单
    handleClickSubMenu(value, index) {
        this.removePageStatus();   // 点击菜单时，清空跳转页面所保存的状态
        window._this = this;
        let token = app.getToken();
        if (!token) {
            this.handleConsoleToken();
        } else {
            let isOpenKey = app.getData('subMenuKeyPlatform');
            if (isOpenKey) {
                if (isOpenKey != value.key) {
                    app.setData('subMenuKeyPlatform', value.key);
                    this.setState({
                        openSubMenuKey: value.key,
                    })
                } else {
                    app.removeDate('subMenuKeyPlatform');
                    this.setState({
                        openSubMenuKey: '',
                    })
                }
            } else {
                app.setData('subMenuKeyPlatform', value.key);
                this.setState({
                    openSubMenuKey: value.key,
                })
            }
        }
    }

    // 清除当前点击的通知
    // requestClearNotice(type) {
    //     app.post(orders.UPDATE_NOTICE, {notice_type: type}).then((req) => {
    //         if (req.code == 1) {
    //             this.requestNotice();   // 查看所有通知
    //         }
    //     })
    // }

    // 点击菜单时，清空跳转页面所保存的状态
    removePageStatus() {
        app.removeDate('saleActivity');  ////促销活动页面---点击某一类目的查看活动商品按钮跳转页面时  保存促销活动之前所在的状态，防止页面重新刷新
    }

    handleConsoleToken() {
        app.alert('请重新登录', 'error', 3);
        this.props.history.push(path + '/login');
    }

    //点击左侧的列表
    handleMenuClick({key}) {
        app.scrollTop();
        this.removePageStatus();   // 点击菜单时，清空跳转页面所保存的状态
        app.removeDate('pageStatus');
        window._this = this;
        let token = app.getToken();
        if (!token) {
            this.handleConsoleToken();
        } else {
            //this.requestNotice();   //查看所有通知
            const re = this.state.menuList.filter(item => {
                if (item.subList) {
                    const subRe = item.subList.filter(subItem => {
                        return subItem.path === key;
                    });
                    if (subRe.length > 0) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return item.path === key;
                }
            });
            if (re.length > 0) {
                let title = "";
                const list = re[0];
                if (list.subList) {
                    const subRe = list.subList.filter(subItem => {
                        return subItem.path === key;
                    });
                    title = subRe[0].title;
                } else {
                    title = list.title;
                }
                const pathList = [title];
                this.setState({
                    pathList
                });
            }

            this.setState({
                currentKey: key
            });

            app.setData('pathPlatform', key);
            this.props.history.push(key);
        }
    }

    // 点击退出按钮
    handleExit() {
        let _this = this;
        confirm(
            {
                title: '',
                content: '您确定要退出吗？',
                okText: '确定',
                cancelText: '取消',
                onOk() {
                    app.removeToken();
                    _this.props.history.push(path + "/login");
                },
                onCancel() {
                },
            });
    }
}

export default Home;

